package com.bawei.viewmodel_livedata_test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

/**
 * 举例：activity数字显示，点击按钮每次数字+1，当屏幕旋转，观察数字变化
 * 现象：当屏幕旋转，activity生命周期重新执行，num重新赋值
 * 解决：使用viewModel,因为viewModel一直存活
 */
public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    private NumViewModel mNumViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = findViewById(R.id.tv);
        mNumViewModel = new ViewModelProvider(this).get(NumViewModel.class);
        mTextView.setText(mNumViewModel.num+"");
    }
    //加
    public void plus(View view) {
//        num++;
        mTextView.setText(++mNumViewModel.num+"");
    }
}